package game.leon.seawar.server.handler;

import game.leon.engine.net.GameSession;
import game.leon.engine.pattern.Fun;
import game.leon.engine.utils.LinkedNode;
import game.leon.seawar.vo.BaseVO;
import game.leon.seawar.vo.RemoteMessage;

import java.io.IOException;

/**
 * User: BianP
 * Date: 11-12-31
 */
class FunSuit <T extends BaseVO> implements
        FunList<T, BaseVO>,
        Handler<T> {
    private LinkedNode<Fun<FunParam<T>, BaseVO>> funList;
    public FunSuit(Fun<FunParam<T>, BaseVO>... args) {
        for(Fun<FunParam<T>, BaseVO> fun : args) {
            addFun(fun);
        }
    }
    @Override
    public void addFun(Fun<FunParam<T>, BaseVO> fun) {
        funList = LinkedNode.cons(fun, funList);
    }
    @Override
    public RemoteMessage handle(GameSession session, int message, T data) throws IOException {
        FunParam<T> param = new FunParam<T>(session, message, data);
        BaseVO result = null;
        LinkedNode<Fun<FunParam<T>, BaseVO>> node = funList;
        while (node != null) {
            Fun<FunParam<T>, BaseVO> fun = node.getItem();
            BaseVO perResult = fun.exec(param);
            if (result == null && perResult != null) {
                result = perResult;
            }
            node = node.getNext();
        }
        // 这里处理携带的消息
        if (result == null) return null;
        return new RemoteMessage(0, result);
    }
}
